#include "joypad.h"
#include <string.h>

CJoyPad::CJoyPad()
{
  Reset();
}

void
CJoyPad::Reset()
{
  memset(this, 0, sizeof(*this));
}

void
CJoyPad::SetKeyState(int index, u8 key, u8 down)
{
  if (down) {
    m_KeyState[index] |= key;
  } else {
    m_KeyState[index] &= ~key;
  }
}

u8
CJoyPad::ReadState(int index)
{
  u32& key_index = m_KeyIndex[index];
  u8 data = (((m_KeyState[index] >> key_index) & 1) | 0x40);
  key_index = ((key_index >= 24) ? 0 : (key_index + 1));
  return data;
}

void
CJoyPad::WriteState(int index, u8 state)
{
  u8& orig = m_JoyPadReg[index];
  if (!(orig&1) && (state&1)) {
    m_KeyIndex[0] = m_KeyIndex[1] = 0;
  }
  orig = state;
}
